<template>
  <div class="book-details-container">
    <div v-if="currentBook.length > 0" class="book-details">
      <div class="book-image">
        
        <img v-if="currentBook[0][0].img" :src="currentBook[0][0].img" alt="图书封面" />
        <div class="image-overlay">
          <div class="overlay-content">点击查看大图</div>
        </div>
      </div>
      <div class="book-info">
        <h1 class="book-title">{{ currentBook[0][0].bookname }}</h1>
        <div class="book-meta">
          <p class="author"><i class="author-icon"></i>作者：{{ currentBook[0][0].author }}</p>
          <p class="publisher"><i class="publisher-icon"></i>出版社：{{ currentBook[0][0].publish }}</p>
        </div>
        
        <div class="price-section">
          <div class="price-label">价格</div>
          <div class="price-value">¥{{ currentBook[0][0].price }}</div>
          <div class="stock-info">库存：{{ currentBook[0][0].stock }} 件</div>
        </div>
        
        <div class="book-intro">
          <h3>图书简介</h3>
          <div class="intro-content" v-if="currentBook[0][0].intro">{{ currentBook[0][0].intro }}</div>
          <div class="intro-content" v-else>暂无图书简介信息</div>
        </div>
        
        <div class="purchase-section">
          <div class="quantity-control">
            <span>数量：</span>
            <div class="quantity-actions">
              <button @click="quantity > 1 ? quantity-- : quantity" class="quantity-btn minus">-</button>
              <input type="number" v-model="quantity" min="1" max="99" class="quantity-input" />
              <button @click="quantity < currentBook[0][0].stock ? quantity++ : quantity" class="quantity-btn plus">+</button>
            </div>
          </div>
          
          <div class="actions">
            <button @click="addToCart" class="add-to-cart-btn">
              <i class="cart-icon"></i> 加入购物车
            </button>
            <button @click="buyNow" class="buy-now-btn">立即购买</button>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="loading">
      <p>正在加载图书信息...</p>
      <div class="loading-spinner"></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useShopcartStore } from "@/stores/shopcart";
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const shopcartStore = useShopcartStore();
const bookId = route.params.id || route.query.id;
const bookData = ref(null); // 原始数据
const quantity = ref(1);

// 获取当前书籍数据（确保返回数组格式）
const currentBook = computed(() => {
  if (!bookData.value) return [];
  
  // 如果已经是数组，直接返回
  if (Array.isArray(bookData.value)) {
    return bookData.value;
  }
  
  // 如果是对象，转为包含该对象的数组
  return [bookData.value];
});

const fetchBookDetails = async () => {
  if (!bookId) {
    ElMessage.error('图书ID不存在');
    return;
  }
  
  try {
    const res = await axios.get(`/api/booksDetails/${bookId}`);
    
    if (res.data.code === 200) {
      // 保存原始数据，由计算属性处理转换
      bookData.value = res.data.data;
      
      // 更精确的空数据检查
      if (!bookData.value || (Array.isArray(bookData.value) && bookData.value.length === 0)) {
        ElMessage.error('未找到图书详情');
      }
    } else {
      ElMessage.error(res.data.message || '获取图书详情失败');
    }
  } catch (err) {
    console.error('获取图书详情错误:', err);
    ElMessage.error('获取图书详情失败: ' + (err.message || '未知错误'));
  }
};

// 添加到购物车
const addToCart = async () => {
  if (!currentBook.value || !Array.isArray(currentBook.value) || currentBook.value.length === 0) {
    ElMessage.warning('无效的图书信息');
    return;
  }
  
  if (!sessionStorage.getItem('token')) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  try {
    const bookItem = currentBook.value[0][0]; // 获取数组中的第一个元素
    const result = await shopcartStore.addToCart(bookItem.b_id, quantity.value);
    
    if (result && result.success) {
      ElMessage.success(`成功将《${bookItem.bookname}》加入购物车`);
    } else {
      ElMessage.error(result?.message || '添加购物车失败');
    }
  } catch (error) {
    console.error('添加购物车错误:', error);
    ElMessage.error('添加购物车失败: ' + (error.message || '未知错误'));
  }
};

// 立即购买
const buyNow = async () => {
  try {
    await addToCart();
    router.push('/shopcart');
  } catch (error) {
    console.error('立即购买错误:', error);
  }
};

// 监听路由参数变化，重新获取图书详情
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchBookDetails();
  }
});

onMounted(() => {
  fetchBookDetails();
});
</script>

<style scoped>
.book-details-container {
  max-width: 1200px;
  margin: 30px auto;
  padding: 30px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.08);
  border-radius: 10px;
  background: #fff;
}

.book-details {
  display: flex;
  gap: 40px;
}

.book-image {
  flex: 0 0 300px;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.book-image:hover {
  transform: translateY(-5px);
}

.book-image img {
  width: 100%;
  height: auto;
  display: block;
  object-fit: contain;
  background-color: #f8f8f8;
  min-height: 400px;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.book-image:hover .image-overlay {
  opacity: 1;
}

.overlay-content {
  color: white;
  font-size: 16px;
  padding: 10px 15px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20px;
}

.book-info {
  flex: 1;
}

.book-title {
  margin: 0 0 15px;
  color: #333;
  font-size: 28px;
  line-height: 1.3;
  font-weight: 600;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.book-meta {
  margin-bottom: 25px;
}

.book-meta p {
  margin: 8px 0;
  font-size: 16px;
  color: #666;
  position: relative;
  padding-left: 5px;
}

.price-section {
  background-color: #f9f9f9;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 25px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.price-label {
  font-size: 16px;
  color: #666;
  margin-right: 15px;
}

.price-value {
  font-size: 28px;
  color: #e53935;
  font-weight: bold;
  margin-right: auto;
}

.stock-info {
  font-size: 14px;
  color: #888;
  background-color: #f0f0f0;
  padding: 3px 10px;
  border-radius: 20px;
}

.book-intro {
  margin-bottom: 30px;
}

.book-intro h3 {
  font-size: 18px;
  margin: 0 0 10px;
  color: #333;
  position: relative;
  padding-left: 12px;
  border-left: 4px solid #e53935;
}

.intro-content {
  font-size: 15px;
  line-height: 1.7;
  color: #555;
  text-align: justify;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.purchase-section {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-control span {
  margin-right: 15px;
  font-size: 16px;
  color: #666;
}

.quantity-actions {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border: 1px solid #ddd;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.2s;
}

.quantity-btn:hover {
  background-color: #f0f0f0;
}

.quantity-btn.minus {
  border-radius: 4px 0 0 4px;
}

.quantity-btn.plus {
  border-radius: 0 4px 4px 0;
}

.quantity-input {
  width: 50px;
  height: 36px;
  text-align: center;
  border: 1px solid #ddd;
  border-left: none;
  border-right: none;
  font-size: 16px;
}

.actions {
  display: flex;
  gap: 15px;
}

.add-to-cart-btn, .buy-now-btn {
  padding: 12px 25px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s;
}

.add-to-cart-btn {
  background-color: #ff9800;
  color: white;
  flex: 1;
  position: relative;
}

.buy-now-btn {
  background-color: #e53935;
  color: white;
  flex: 1;
}

.add-to-cart-btn:hover {
  background-color: #f57c00;
  transform: translateY(-2px);
}

.buy-now-btn:hover {
  background-color: #d32f2f;
  transform: translateY(-2px);
}

.loading {
  text-align: center;
  padding: 60px 0;
}

.loading p {
  font-size: 18px;
  color: #666;
  margin-bottom: 20px;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #e53935;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .book-details-container {
    padding: 15px;
  }
  
  .book-details {
    flex-direction: column;
  }
  
  .book-image {
    flex: none;
    margin-bottom: 20px;
    max-width: 250px;
    margin-left: auto;
    margin-right: auto;
  }
  
  .book-image img {
    min-height: 320px;
  }
  
  .actions {
    flex-direction: column;
  }
  
  .book-title {
    font-size: 22px;
  }
  
  .price-value {
    font-size: 24px;
  }
}
</style>
  